<!DOCTYPE html>
<html lang="zh-cn">

	<head>
		<meta charset="UTF-8">
		<title class="title">[文件管理器]</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<style type="text/css">
			.content {background: transparent;}
			.btn {position: relative;top: 0;left: 0;bottom: 0;right: 0;}
			.btn .file {position: fixed;z-index: 93;left: 0;right: 0;top: 0;bottom: 0;width: 100%;opacity: 0;}
		</style>
	</head>

	<body>
		
		<div id="content" class="content">
			<div v-show="!disabled" class="btn">
				<input @change="onChange" :accept="accept" ref="file" class="file" type="file" />
			</div>
		</div>
		
		<script type="text/javascript" src="js/vue.min.js"></script>
		<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			var xhr;
			var vm = new Vue({
				el: '#content',
				data: {
					accept: '',
					disabled: false
				},
				mounted() {
					let fileDom = this.$refs.file;
					fileDom.value = '';
					console.log('加载webview');
				},
				methods: {
					onChange(e) {
						let fileDom = this.$refs.file;
						let file = fileDom.files[0];
						let {size = 10} = plus.webview.currentWebview();
						// 限制文件小于10M,可自行修改
						if(file.size > (1024*1024 * Math.abs(size))) {
							plus.nativeUI.toast(`附件大小请勿超过${size}M`);
							return;
						}
						this.createUpload(file);
					},
					createUpload(file) {
						let {debug = false,url,name = 'file',method = 'POST',header = {},formData:data = {}} = plus.webview.currentWebview();
						if (!url) {console.error('url为必传参数');return;}
						data['fileName'] = file.name;
						
						debug&&console.log(`
						上传接口地址:${url}\n
						附件key:${name}\n 
						附件名称:${file.name}\n 
						附件大小:${file.size}\n
						请求头:${JSON.stringify(header)}\n
						参数:${JSON.stringify(data)}
						`);
						
						let formData = new FormData();
						for (let keys in data) {formData.append(keys, data[keys]);}
						formData.append(name, file);
						xhr = new XMLHttpRequest();
						xhr.open(method, url, true);
						for (let keys in header) {xhr.setRequestHeader(keys, header[keys]);}
						
						xhr.upload.addEventListener("progress",(event) => {
							if(event.lengthComputable){
								let percent = Math.ceil(event.loaded * 100 / event.total);
								if (percent <= 100) {
									location.href = 'callback?retype=percent&percent=' + escape(percent);
								}
							}
						}, false);
						
						xhr.ontimeout = function(){
							this.disabled = false;
							location.href = 'callback?retype=complete&status=408&msg=' + escape('请求超时');
						};
						
						xhr.onreadystatechange = (ev) => {
							if(xhr.readyState == 4) {
								let fileDom = this.$refs.file;
								fileDom.value = '';
								this.disabled = false;
								if (xhr.status == 200) {
									debug&&console.log('上传完成：'+xhr.responseText);
									location.href = `callback?retype=complete&fileName=${escape(file.name)}&responseText=${escape(xhr.responseText)}&success=true&status=${xhr.status}&msg=${escape('上传成功')}`;
									return;
								}
								else if (xhr.status == 0) {
									console.error('status = 0 :请检查请求头Content-Type与服务端是否匹配，服务端已正确开启跨域，并且nginx未拦截阻止请求');
								}
								location.href = `callback?retype=complete&fileName=${escape(file.name)}&status=${xhr.status}&msg=${escape('上传失败')}`;
							}
						};
						this.disabled = true;
						xhr.send(formData);
						
						/**
						 * ajax 相关
						 */
						// try{
						// 	// plus.nativeUI.showWaiting("正在上传");
						// 	let file = fileDom.files[0]
						// 	const aliyunServerURL = param.host
						// 	var policyBase64 = param.policy;
						// 	var signature = param.signature;
						// 	var filePathName = param.dir + "/" + file.name;
						// 	var fileFullName = aliyunServerURL + "/" + filePathName;
						// 	const aliyunFileKey = param.dir + new Date().getTime() + Math.floor(Math.random() * 100) + file.name
						// 	var request = new FormData();
						// 	request.append('OSSAccessKeyId', param.accessid);
						// 	request.append('policy', policyBase64);
						// 	request.append('Signature', signature);
						// 	request.append('key', filePathName);
						// 	request.append('callback', param.callback);
						// 	request.append('file', file);
						// 	let myXhr = new XMLHttpRequest();  // 监听上传
						// 	$.ajax({
						// 		url: aliyunServerURL,
						// 		data: request,
						// 		processData: false,
						// 		cache: false,
						// 		async:true,
						// 		contentType: false,
						// 		//关键是要设置contentType 为false，不然发出的请求头 没有boundary
						// 		//该参数是让jQuery去判断contentType
						// 		type: "POST",
						// 		xhr: function() {        //ajax进度条，直接拿过去就可以用
						// 			myXhr = $.ajaxSettings.xhr();
						// 			if(myXhr.upload){ 
						// 				tis.style.display = 'flex';
						// 				myXhr.upload.addEventListener('progress',function(e){                            
						// 					var loaded = e.loaded;                  //已经上传大小情况 
						// 					var total = e.total;                      //附件总大小 
						// 					var num = Math.floor(100*loaded/total);             // 附件进度
						// 					var percent = Math.floor(100*loaded/total)+"%";     //已经上传的百分比 
						// 					progressV.value = num // 进度条
						// 					progress.innerText = `努力上传中..${percent}`;
						// 				}, false); 
						// 				// cancel.addEventListener("click", ()=>{
						// 				// 	xhr.abort();
						// 				// 	plus.webview.currentWebview().close();
						// 				// });
						// 			}
						// 			return myXhr;
									
						// 		},
						// 		success: function (res) {
						// 			plus.nativeUI.closeWaiting()
						// 			// 对full_filename进行处理  如果是http 开头会进行加密
						// 			// res.data.full_filename = res.data.full_filename.substring(4,res.data.full_filename.length)
						// 			let d = JSON.stringify(res.data)
						// 			location.href = `callback?fileName=${escape(file.name)}&d=${escape(d)}`;
						// 			// 关闭页面
						// 			setTimeout(()=>{
						// 				tis.style.display = 'none';
						// 				plus.webview.currentWebview().close();
						// 			},300);
						// 		},
						// 		error:function(res){
						// 			setTimeout(()=>{
						// 				tis.style.display = 'none';
						// 				plus.webview.currentWebview().close();
						// 			},1000);
						// 			plus.nativeUI.closeWaiting()
						// 			plus.nativeUI.toast("上传失败，请稍后重试")
						// 			console.log(JSON.stringify(res) )
						// 		}
						// 	});
						// }catch(e){
						// 	console.log(e)
						// 	plus.nativeUI.closeWaiting()
						// 	plus.nativeUI.toast("上传失败，请稍后重试")
						// 	//TODO handle the exception
						// }
					}
				}
			});
			
		</script>
	</body>

</html>
